package cn.hackcloud.concurrency.future;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * 当提交任务时创建一个新的线程来受理该任务
 * 进而达到任务异步执行的结果
 * Created by www.ibfbc.com
 */
public class FutureServiceImpl<IN, OUT> implements FutureService<IN, OUT> {
    //为线程名指定前缀，这是一个好习惯
    private final static String FUTURE_THREAD_PREFIX = "FUTURE-";

    private final AtomicInteger nextCounter = new AtomicInteger(0);

    private String getNextName() {
        return FUTURE_THREAD_PREFIX + nextCounter.incrementAndGet();
    }

    /**
     * 任务执行结束后、将null结果传递给future
     */
    @Override
    public Future<?> submit(Runnable runnable) {
        final FutureTask<Void> future = new FutureTask<>();
        new Thread(() -> {
            runnable.run();
            future.finish(null);
        }, getNextName()).start();
        return future;
    }

    /**
     * 任务执行结束后、将真实的结果通过finish方法传递给future
     */
    @Override
    public Future<OUT> submit(Task<IN, OUT> task, IN input) {
        final FutureTask<OUT> future = new FutureTask<>();
        new Thread(() -> {
            OUT result = task.get(input);
            future.finish(result);
        }, getNextName()).start();
        return future;
    }

    @Override
    public Future<OUT> submit(Task<IN, OUT> task, IN input, Callback<OUT> callback) {
        final FutureTask<OUT> future = new FutureTask<>();
        new Thread(() -> {
            OUT result = task.get(input);
            future.finish(result);
            //执行回调接口
            if (null != callback) {
                callback.call(result);
            }
        }, getNextName()).start();
        return future;
    }
}
